package dao;

import bean.Person;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import java.util.List;

public class PersonDAOImpl implements PersonDAO {
    // sql会话
    private Session session;
    // sql事务
    private Transaction transaction;
    private boolean completed;
    
    public PersonDAOImpl(Session session) {
        this.session = session;
    }

    @Override
    public boolean add(Person person) {
        try {
            // 开始工作单元并返回关联的事务对象
            transaction = session.beginTransaction();
            // 为序列化实例分配生成的标识符并保存
            session.save(person);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            // 提交当前资源事务，将任何未流动的更改写入数据库
            transaction.commit();
        }
        return completed;
    }

    @Override
    public boolean modify(Person person) {
        try {
            transaction = session.beginTransaction();
            // 使用给定的独立实例的标识符更新持久实例
            session.update(person);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return completed;
    }

    @Override
    public boolean remove(int personId) {
        try {
            transaction = session.beginTransaction();
            // 使用给定标识符返回给定实体类的持久实例，如果没有此类持久实例，则返回null
            Person person = session.get(Person.class, personId);
            // 从数据存储中删除持久实例
            session.delete(person);
            completed = true;
        } catch (Exception e) {
            completed = false;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return completed;
    }

    @Override
    public List<Person> queryAll() {
        List<Person> persons;
        try {
            @SuppressWarnings("unchecked")
            // 为给定的HQL/JPQL查询字符串创建查询实例
            Query<Person> query = session.createQuery("FROM Person");
            persons = query.list();
        } catch (Exception e) {
            persons = null;
            e.printStackTrace();
        }
        return persons;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Person query(int personId) {
        Person person;
        try {
            transaction = session.beginTransaction();
            Query<Person> query = session.createQuery("FROM Person WHERE personId=" + personId);
            person = (Person) query.list().get(0);
        } catch (Exception e) {
            person = null;
            e.printStackTrace();
        } finally {
            transaction.commit();
        }
        return person;
    }
}
